// 自定义hooks
import { useDispatch, useSelector } from "react-redux"
import { inititalState } from "@/types/store"
import { useEffect, useRef } from "react"
import { RootState } from "@/types/store"
import { useHistory } from "react-router-dom"
import { Dialog } from "antd-mobile"
const useInitialState: inititalState = (action, properName) => {
  const dispatch = useDispatch()
  const state = useSelector((state: RootState) => state[properName])
  const actionRef = useRef(action)
  useEffect(() => {
    const action = actionRef.current
    dispatch(action())
  }, [dispatch])
  return state
}
// 退出页面时重置
const useResetState = <KeyName extends keyof RootState>(stateName: KeyName) => {
  const dispatch = useDispatch()
  useEffect(() => {
    return () => {
      dispatch({ type: "reset", payload: stateName })
    }
  }, [dispatch, stateName])
}

const useAuthSet = () => {
  const history = useHistory<{ from: string }>()
  const token = useSelector((state: RootState) => state.login.token)
  useEffect(() => {
    if (!token) {
      const hander = Dialog.show({
        content: "您当前没有登录，如需评论,需要先进行登录注册,您是否还要进行评论",
        closeOnAction: true,
        actions: [
          [
            {
              key: "down",
              text: "放弃评论",
              onClick: () => hander.close(),
              style: {
                color: "var(--adm-color-weak)",
              },
            },
            {
              key: "go",
              text: "去登录",
              onClick: () =>
                history.push("/login", {
                  from: history.location.pathname,
                }),
            },
          ],
        ],
      })
    }
  }, [token, history])
  return !!token
}
export { useInitialState, useResetState, useAuthSet }
